package com.example.aipdefficiency.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class JwtUtil {
    
    private static final String SECRET = "ai-p-d-efficiency-secret-key";
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; // 24小时
    
    public String generateToken(Long userId, String username) {
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create()
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
    }
    
    public DecodedJWT verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(token);
    }
    
    public Long getUserId(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getClaim("userId").asLong();
    }
    
    public String getUsername(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getClaim("username").asString();
    }
    
    public boolean isTokenExpired(String token) {
        DecodedJWT decodedJWT = verifyToken(token);
        return decodedJWT.getExpiresAt().before(new Date());
    }
} 